// nestable.js
// ====================================================================
// This file should not be included in your project.
// This is just a sample how to initialize plugins or components.
//
// - ThemeOn.net -


$(document).ready(function () {
	
    /**
     * Switchery checkbox
     * @type {HTMLElement | null}
     */
    var changeCheckbox =document.getElementById('demo-sw')
    var isEnableSwitchery = new Switchery(changeCheckbox);

    var no_parentCheckbox =document.getElementById('no_parent')
    var noParentSwitchery = new Switchery(no_parentCheckbox);

    /**
     * checkbox change
     */
    changeCheckbox.onchange = function() {
        if(!changeCheckbox.hasAttribute("checked")){
            $("#demo-sw").attr("checked", true);
        }else{
            $("#demo-sw").removeAttr("checked");
        }
        changeCheckbox.check==true?changeCheckbox.check=false:changeCheckbox.check=true;
    };

    /**
     * no parent department select value == 0
     */
    no_parentCheckbox.onchange = function() {
        $("#loaddepart option[value='0']").attr("selected", "selected");
        $('#loaddepart').selectpicker('refresh');
    };

    $.ajax({
        //几个参数需要注意一下
        type: "get",//方法类型
        dataType: "json",//预期服务器返回的数据类型
        url: "/system/department/getDepartmentTree" ,//url
        // data: ,
        success: function (result) {

            $("#depart_tree").append(getDepartment(result))

            $("#depart_tree").jstree({
                "plugins" : [ "search" ]
            });
        },
        error : function() {
            alert("获取部门树异常！");
        }
    })


    var to = false;
    $('#input-tree').keyup(function () {
        if(to) { clearTimeout(to); }
        to = setTimeout(function () {
            var v = $('#input-tree').val();
            $('#depart_tree').jstree(true).search(v);
        }, 250);
    });

    $('#depart_tree').bind("activate_node.jstree", function (obj, e) {
        // 处理代码
        // 获取当前节点
        var currentNode = e.node;
        if(currentNode){
            $.ajax({
                //几个参数需要注意一下
                type: "get",//方法类型
                dataType: "json",//预期服务器返回的数据类型
                url: "/system/department/getDepartmentDetail" ,//url
                data: {id:currentNode.data.id},
                success: function (result) {
                	$("input[name='departname']").val(result.name);
                    $("input[name='departname']").attr("id",result.id)
                	$("input[name='code']").val(result.code);
                	$("input[name='icon']").val(result.icon);
                	$("#demo-textarea-input").val(result.REMARK);
                	if(result.enable == 1){
                        setSwitchery(isEnableSwitchery,true)
                	}else{
                        setSwitchery(isEnableSwitchery,false)
                	}
                	// new Switchery(changeCheckbox);
                    var loaddepart = $('#loaddepart');
                    loaddepart.empty();
                	if(result.parentid != 0){
                        var parentid = currentNode.parent ;
                            parentnode = $('#depart_tree').jstree("get_node", parentid);
                        loaddepart.append("<option value='"+parentnode.data.id+"' selected>"+parentnode.text+"</option>");
                        loaddepart.selectpicker('refresh');
                        setSwitchery(noParentSwitchery,false)
                	}else{
                        loaddepart.append("<option value='0' selected>no thing select</option>");
                        loaddepart.selectpicker('refresh');
                        setSwitchery(noParentSwitchery,true)
                    }
                },
                error : function() {
                    alert("获取部门详情失败！");
                }
            })
        }
    });


    // jQuery(function($){
    // $('.dd').nestable();
    //     $('.dd-handle a').on('mousedown', function(e){
    //         e.stopPropagation();
    //     });
    //     $('[data-rel="tooltip"]').tooltip();
    //     $('#nestable').nestable().on('change', function(){
    //         var r = $('.dd').nestable('serialize');
    //         $("#xx").html(JSON.stringify(r));    //改变排序之后的数据
    //     });
    //     // $('#nestable').nestable().on('change', updateOutput);
    // });

    // $("#nestable").nestable({group: 1}).on("change", updateOutput);
    // $("#nestable2").nestable({group: 1}).on("change", updateOutput);
    // updateOutput($("#nestable").data("output", $("#nestable-output")));
    // updateOutput($("#nestable2").data("output", $("#nestable2-output")));

    // jQuery(function($){
/*
    $('.dd').nestable({
        maxDepth : 10,//最大层级
    });
    $(".dd").nestable("collapseAll");
    $(".dd").on("change", updateOutput);
    // updateOutput($('.dd').data("output", $("#nestable-output")));

    $('.dd-handle a').on('mousedown', function (e) {
        e.stopPropagation();
    });

    $('[data-rel="tooltip"]').tooltip();

    // });
    //点击删除
    $('.pull-right').on('click', function (e) {
        var id = $(e.target).parents(".dd-item").data("id");
        e.stopPropagation();
    });
    //点击内容选中
    $('.dd2-content').on('click', function (e) {
        // var target = $(e.target);
        // $(e.target).toggleClass("selected");
        var id = $(e.target).parent().data("id");
        e.stopPropagation();
    });
*/


});

/**
 * 选中颜色
 * @param e
 */
/*function toggleSelect(e) {
    var target = $(e);
    target.toggleClass("selected");
}*/

/**
 * 展开/收起
 */
$("#nestable-menu").on("click", function (e) {
    var target = $(e.target);
    var instance =  $("#depart_tree").jstree(true);
    if (target.hasClass("btn-success")) {
        instance.close_all();
        target.text("展开全部");

    } else {
        target.text("收起全部");
        instance.open_all();
    }
    target.toggleClass("btn-success");
})

/**
 * onchange事件
 * @param e
 */
/*var updateOutput = function (e) {
    var list = e.length ? e : $(e.target), output = list.data("output");
    // if (window.JSON) {
    //     output.val(window.JSON.stringify(list.nestable("serialize")))
    // } else {
    //     output.val("浏览器不支持")
    // }
    console.log(window.JSON.stringify(list.nestable("serialize")))
};*/

var loadDepart = function (e) {
    var target = $(e.target);
    target.val();

}

/**
 * 构建部门数html
 * @param depart_json
 * @returns {string}
 */
var getDepartment = function (depart_json) {
    var html = '<ul>';
    for (var i=0,l=depart_json.length;i<l;i++) {
        // for (var d in depart_json[i]) {
        html+=
            '<li data-id="'+depart_json[i].id+'" data-jstree="{&quot;opened&quot;:true, &quot;icon&quot;:&quot;'+depart_json[i].icon+'&quot;}">'+depart_json[i].name
         //如果存在子节点
        if (depart_json[i].children && depart_json[i].children.length != 0){

                html += getDepartment(depart_json[i].children);
        }
        // }
        html+='</li>'
    }

    html+='</ul>'
    return html;
}

/**
 * 点击下拉框动态获取列表
 */
$('#loaddepart').on('shown.bs.select', function (e) {
    // do something...
    // console.log("do something");
    // $('#loaddepart').append("<option value='222'>请选择</option>");
    $('#loaddepart').empty();
    $.ajax({
        //几个参数需要注意一下
        type: "get",//方法类型
        dataType: "json",//预期服务器返回的数据类型
        url: "/system/department/getDepartmentList" ,//url
        // data: ,
        success: function (result) {
            var html = "";
            for(var i=0,l=result.length;i<l;i++){
                html += "<option value='"+result[i].id+"'>"+result[i].name+"</option>";
            }
            html += "<option value='0'>no thing select</option>";
            $('#loaddepart').append(html);
            $('#loaddepart').selectpicker('refresh');
        },
        error : function() {
            alert("获取部门树异常！");
        }
    })

});

//点击内容选中
$('.selectpicker').on('click', function (e) {
    // var target = $(e.target);
    // $(e.target).toggleClass("selected");
    var target = $(e.target);
    target.val();
});

/*
 * 切换Switchery开关函数
 * * switchElement Switchery对象
 * * checkedBool 选中的状态
 */
function setSwitchery(switchElement, checkedBool) {
    if ((checkedBool && !switchElement.isChecked()) || (!checkedBool && switchElement.isChecked())) {
        switchElement.setPosition(true);
        switchElement.handleOnchange(true);
    }
}